﻿using System.Data;
using System.IO;
using System.Web;
using System.Text;
using System;

namespace MSL.Utility.Doc
{
    /// <summary>
    /// CSV文件转换类
    /// </summary>
    public class Csv
    {
        private static Csv _instance;
        private static readonly object _lock = new Object();
        /// <summary>
        /// 
        /// </summary>
        private Csv()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }

        #region 单一实例

        /// <summary>
        /// 返回唯一实例
        /// </summary>
        public static Csv Instance
        {
            get
            {
                return GetInstance();
            }
        }
        /// <summary>
        /// 获得单一实例
        /// </summary>
        /// <returns></returns>
        private static Csv GetInstance()
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new Csv();
                    }
                }
            }
            return _instance;
        }
        #endregion

        #region 导出报表为Csv

        /// <summary>
        /// 导出报表为Csv
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="strFilePath">物理路径</param>
        /// <param name="tableHeader">表头</param>
        /// <param name="columName">字段标题,逗号分隔</param>
        public bool DataTableToCSV(DataTable dt, string strFilePath, string tableHeader, string columName)
        {
            try
            {
                string strBufferLine = "";
                StreamWriter strmWriterObj = new StreamWriter(strFilePath, false, System.Text.Encoding.UTF8);
                strmWriterObj.WriteLine(tableHeader);
                strmWriterObj.WriteLine(columName);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    strBufferLine = "";
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j > 0)
                            strBufferLine += ",";
                        strBufferLine += dt.Rows[i][j].ToString();
                    }
                    strmWriterObj.WriteLine(strBufferLine);
                }
                strmWriterObj.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region 将Csv读入DataTable

        /// <summary>
        /// 将Csv读入DataTable
        /// </summary>
        /// <param name="filePath">csv文件路径</param>
        /// <param name="n">表示第n行是字段title,第n+1行是记录开始</param>
        public DataTable CSVToDataTable(string filePath, int n)
        {
            DataTable dt = null;
            StreamReader reader = new StreamReader(filePath, System.Text.Encoding.UTF8, false);
            int i = 0, m = 0;
            reader.Peek();
            while (reader.Peek() > 0)
            {
                m = m + 1;
                string str = reader.ReadLine();
                if (m >= n + 1)
                {
                    string[] split = str.Split(',');

                    System.Data.DataRow dr = dt.NewRow();
                    for (i = 0; i < split.Length; i++)
                    {
                        dr[i] = split[i];
                    }
                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }

        #endregion

        #region 获得Csv文件
        /// <summary>
        /// 获得Csv文件
        /// </summary>
        /// <param name="data">数据表</param>
        /// <returns>CSV字符串数据</returns>
        public string DataTableToCSV(DataTable data)
        {
            StringBuilder sb = new StringBuilder();
            // 写出表头
            foreach (DataColumn dc in data.Columns)
            {
                sb.Append(dc.ColumnName.ToString() + ",");
            }
            sb.Append("\n");
            // 写出数据
            foreach (DataRowView dataRowView in data.DefaultView)
            {
                foreach (DataColumn DataColumn in data.Columns)
                {
                    sb.Append(dataRowView[DataColumn.ColumnName].ToString() + ",");
                }
                sb.Append("\n");
            }
            return sb.ToString();
        }

        /// <summary>
        /// 获得Csv文件
        /// </summary>
        /// <param name="dataSet">数据集</param>
        /// <returns>CSV字符串数据</returns>
        public StringBuilder DataTableToCSV(DataSet dataSet)
        {
            StringBuilder StringBuilder = new StringBuilder();
            foreach (DataTable data in dataSet.Tables)
            {
                StringBuilder.Append(DataTableToCSV(data));
            }
            return StringBuilder;
        }
        #endregion

        #region 输出Csv文件
        /// <summary>
        /// 在浏览器中输出Csv文件
        /// </summary>
        /// <param name="data">数据表</param>
        /// <param name="fileName">输出文件名</param>
        public void ResponseCSV(DataTable data, string fileName)
        {
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
            HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment;filename=" + fileName);
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.Write(DataTableToCSV(data).ToString());
            HttpContext.Current.Response.End();
        }

        /// <summary>
        /// 在浏览器中输出Csv文件
        /// </summary>
        /// <param name="dataSet">数据权限</param>
        /// <param name="fileName">输出文件名</param>
        public void ResponseCSV(DataSet dataSet, string fileName)
        {
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
            HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment;filename=" + fileName);
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.Write(DataTableToCSV(dataSet).ToString());
            HttpContext.Current.Response.End();
        }
        #endregion
    }
}
